package com.cungmua.app.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.cungmua.app.R;
import com.cungmua.app.base.BaseDrawerActivitys;
import com.cungmua.app.handler.BankListHandler;
import com.cungmua.app.handler.CreateShippingAddressHandler;
import com.cungmua.app.handler.PaymentInfoHandler;
import com.cungmua.app.handler.PlaceOrderHandler;
import com.cungmua.app.model.Bank;
import com.cungmua.app.model.Cart;
import com.cungmua.app.model.PaymentInfo;
import com.cungmua.app.model.PaymentType;
import com.cungmua.app.model.ShippingAddress;
import com.cungmua.app.model.request.BankListRequest;
import com.cungmua.app.model.request.CreateShippingAddressRequest;
import com.cungmua.app.model.request.PaymentInfoRequest;
import com.cungmua.app.model.request.PlaceOrderRequest;
import com.cungmua.app.model.request.UpdateShippingAddressRequest;
import com.cungmua.app.model.response.BankListResponse;
import com.cungmua.app.model.response.CreateShippingAddressResponse;
import com.cungmua.app.model.response.PaymentInfoResponse;
import com.cungmua.app.model.response.PlaceOrderResponse;
import com.cungmua.app.task.BankListTask;
import com.cungmua.app.task.CreateShippingAddressTask;
import com.cungmua.app.task.PaymentInfoTask;
import com.cungmua.app.task.PlaceOrderTask;
import com.cungmua.app.task.UpdateShippingAddressTask;
import com.cungmua.app.utils.AppUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kelvin.nguyen on 6/25/14.
 */
public class MakeOrderActivity extends BaseDrawerActivitys implements PaymentInfoHandler, CreateShippingAddressHandler, PlaceOrderHandler, BankListHandler {
    private TextView txtPhone;
    private TextView txtReceiver;
    private TextView txtAddressString;
    private boolean loggedIn;
    private TextView btnEdit;
    private ShippingAddress address;
    private Spinner spnPaymentType;
    private Spinner spnAddressType;
    private TextView txtSelectAddress;
    private TextView txtCreateAddress;
    private TextView txtNote;
    private ArrayAdapter<PaymentType> paymentTypeAdapter;
    private Button btnBuy;
    private int bankId;
    private List<Bank> bankList = null;
    private ArrayList<String> bankItem = new ArrayList<String>();
    private List<String> listShippingAddr = new ArrayList<String>();
    private List<ShippingAddress> listObShippingAddr = new ArrayList<ShippingAddress>();
    private ShippingAddress chosenAddress = null;
    private String totalPrice = "";
    private long orderId = 0;
    private ImageView icon_home;
    private Button icon_cart;
    private LinearLayout btnCart;
    private LinearLayout rootAddresstype;
    private boolean isShow=false;
    private  PaymentInfo data;

//    private Spinner spnAddressList;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CREATE_ADDRESS) {
            if (resultCode == RESULT_OK) {
                ShippingAddress result = (ShippingAddress) data.getExtras().get(SHIPPING_ADDRESS_KEY);
                CreateShippingAddressRequest request = new CreateShippingAddressRequest(getDeviceId(), getToken());
                request.setAddress(result);
                request.setUserId(getCurrentUser().getId());

                CreateShippingAddressTask task = new CreateShippingAddressTask(this, this);
                task.execute(request);
            } else {
                finish();
            }
        } else if (requestCode == REQUEST_EDIT_ADDRESS) {
            if (resultCode == RESULT_OK) {
                ShippingAddress result = (ShippingAddress) data.getExtras().get(SHIPPING_ADDRESS_KEY);
                UpdateShippingAddressRequest request = new UpdateShippingAddressRequest(getDeviceId(), getToken());
                request.setAddress(result);
                request.setUserId(getCurrentUser().getId());

                UpdateShippingAddressTask task = new UpdateShippingAddressTask(this, this);
                task.execute(request);
            } else {
            }
        } else if (requestCode == REQUEST_PAYMENT) {
            if (resultCode == RESULT_OK) {
//                long orderId = data.getExtras().getLong(IK_ORDER_ID);
                setCurrentCart(new Cart());
                goToFinished(orderId,bankItem);
            } else {
                AlertDialog dialog = new AlertDialog.Builder(this)
                        .setMessage(R.string.payment_fail)
                        .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).show();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_saved_info;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (getCurrentUser().getId() == 0) {
            login();
            loggedIn = false;
        } else {
            loggedIn = true;
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public void updateView() {
        if (loggedIn) {
            PaymentInfoRequest request = new PaymentInfoRequest(getDeviceId(), getToken());
            request.setCityId(getCurrentCity().getId());
            request.setUserId(getCurrentUser().getId());

            PaymentInfoTask task = new PaymentInfoTask(this, this);
            task.execute(request);
        }
    }

    @Override
    public void loadControls(Bundle savedInstanceState) {
        totalPrice = getIntent().getExtras().getString("TOTAL_PRICE");
        txtAddressString = (TextView) findViewById(R.id.txtAddressString);
        txtReceiver = (TextView) findViewById(R.id.txtReceiver);
        txtPhone = (TextView) findViewById(R.id.txtPhone);

        spnPaymentType = (Spinner) findViewById(R.id.spnPaymentType);
        spnAddressType = (Spinner) findViewById(R.id.spnAddressType);
        txtSelectAddress = (TextView) findViewById(R.id.txtSelectAddress);
        txtCreateAddress = (TextView) findViewById(R.id.txtCreateAddress);
        txtNote = (TextView) findViewById(R.id.txtNote);

        btnEdit = (TextView) findViewById(R.id.btnPaymentEdit);
        btnBuy = (Button) findViewById(R.id.btnBuy);

        icon_home=(ImageView)findViewById(R.id.icon_home);
        icon_cart=(Button)findViewById(R.id.icon_cart);
        btnCart=(LinearLayout)findViewById(R.id.btnCart);
        rootAddresstype=(LinearLayout)findViewById(R.id.rootAddresstype);


        Cart currentCart=getCurrentCart();
        icon_cart.setText(currentCart.getTotalQuantity()+"");

        icon_home.setOnClickListener(new ImageView.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMenu();
            }
        });

        btnCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToYourCart();
            }
        });

        txtSelectAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isShow) {
                    rootAddresstype.setVisibility(View.VISIBLE);
                    isShow=true;
                }else {
                    rootAddresstype.setVisibility(View.GONE);
                    isShow=false;
                }
            }
        });

        txtCreateAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MakeOrderActivity.this, CreateShippingAddressActivity.class);
                intent.putExtra(SHIPPING_ADDRESS_KEY,address);
                startActivityForResult(intent, REQUEST_CREATE_ADDRESS);
            }
        });


        spnAddressType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
               // getDistrictData(cityAdapter.getItem(i).getId());
               // alert(data.getAddressList().get(i).getBuildingName());
               // address=data.getAddressList().get(i);
                updateAddressInfo(data.getAddressList().get(i));

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

    }

    public void updateAddressInfo(ShippingAddress shippingAddress){
        txtAddressString.setText(getString(R.string.address_label,shippingAddress.getAddressString()));
        txtPhone.setText(getString(R.string.phone_label, shippingAddress.getPhone()));
        txtReceiver.setText(getString(R.string.receiver_label, shippingAddress.getCustomerName()));
    }
    @Override
    public void onPaymentInfo(PaymentInfoResponse response) {
        if (response.getCode() == 0) {
             data = response.getData();
            if (data.getAddressList().size() > 1) {
                listShippingAddr = new ArrayList<String>();
                listObShippingAddr = new ArrayList<ShippingAddress>();
                for (ShippingAddress item : data.getAddressList()) {
                    listObShippingAddr.add(item);
                    String value = item.getAddressString() + " " + getString(R.string.phone_label, item.getPhone()
                            + " " + getString(R.string.receiver_label, item.getCustomerName()));
                    listShippingAddr.add(value);
                }
                ArrayAdapter<String> shippingListAdapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_dropdown_item);
                shippingListAdapter.addAll(listShippingAddr);
                spnAddressType.setAdapter(shippingListAdapter);

            } else {
                spnAddressType.setVisibility(View.GONE);
            }
            address = data.getDefaultAddress();

            if (address == null) {
                Intent intent = new Intent(this, CreateShippingAddressActivity.class);
                intent.putExtra(SHIPPING_ADDRESS_KEY, new ShippingAddress());
                startActivityForResult(intent, REQUEST_CREATE_ADDRESS);
                return;
            }

            txtAddressString.setText(getString(R.string.address_label,address.getAddressString()));
            txtPhone.setText(getString(R.string.phone_label, address.getPhone()));
            txtReceiver.setText(getString(R.string.receiver_label, address.getCustomerName()));

            paymentTypeAdapter = new ArrayAdapter<PaymentType>(this, android.R.layout.simple_spinner_dropdown_item);
            paymentTypeAdapter.addAll(address.getPaymentList());
            spnPaymentType.setAdapter(paymentTypeAdapter);

            btnEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(MakeOrderActivity.this, CreateShippingAddressActivity.class);
//                    if (listObShippingAddr.size() > 0)
//                        intent.putExtra(SHIPPING_ADDRESS_KEY,chosenAddress);
//                    else
                    intent.putExtra(SHIPPING_ADDRESS_KEY, address);
                    startActivityForResult(intent, REQUEST_EDIT_ADDRESS);
                }
            });

            btnBuy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (paymentTypeAdapter.getItem(spnPaymentType.getSelectedItemPosition()).getId() == 3) { // Chuyen khoan
                        chooseBank();
                    } else {
                        placeOrder();
                    }
                }
            });
        } else {
            alert(response.getMessage());
        }
    }

    private void chooseBank() {
        BankListRequest request = new BankListRequest(getDeviceId(), getToken());
        request.setCityId(getCurrentCity().getId());
        request.setUserId(getCurrentUser().getId());

        BankListTask task = new BankListTask(this, this);
        task.execute(request);
    }

    public void placeOrder() {
        PlaceOrderRequest request = new PlaceOrderRequest(getDeviceId(), getToken());
        request.setCityId(getCurrentCity().getId());
        request.setUserId(getCurrentUser().getId());
//        if (listShippingAddr.size() > 1)
//            request.setShipAddressId(listObShippingAddr.get(spnAddressType.getSelectedItemPosition()).getId());
//        else
        request.setShipAddressId(address.getId());
        request.setProductList(getCurrentCart().toString());
        request.setPaymentType(paymentTypeAdapter.getItem(spnPaymentType.getSelectedItemPosition()).getId());
        request.setVoucherCode("");
        request.setNote(txtNote.getText().toString());
        if (bankId != -1)
            request.setBankId(bankId);

        PlaceOrderTask task = new PlaceOrderTask(MakeOrderActivity.this, MakeOrderActivity.this);
        task.execute(request);
    }

    @Override
    public void onShippingAddressCreated(CreateShippingAddressResponse response) {
        if (response.getCode() == 0)
            refreshActivity();
        else
            alert(response.getMessage());
    }

    @Override
    public void orderPlaced(PlaceOrderResponse response) {
        if (response.getCode() == 0) {
            if (response.getData().getPaymentUrl().isEmpty()) {
                goToFinished(response.getData().getId(), bankItem);
                setCurrentCart(new Cart());
            } else {
                orderId = response.getData().getId();
                Intent intent = new Intent(this, PaymentActivity.class);
                intent.putExtra(IK_PAYMENT_URL, response.getData().getPaymentUrl());
                intent.putExtra(IK_RESULT_URL, response.getData().getResultUrl());
                intent.putExtra(IK_ORDER_ID, response.getData().getId());
                startActivityForResult(intent, REQUEST_PAYMENT);
            }
        } else {
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setMessage(response.getMessage())
                    .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).show();
        }


    }

    @Override
    public void onListBank(BankListResponse response) {
        if (response.getCode() == 0) {
            bankList = response.getData();
            CharSequence[] seq = new CharSequence[bankList.size()];

            for (int i = 0; i < bankList.size(); i++)
                seq[i] = bankList.get(i).getName();

            new AlertDialog.Builder(this)
                    .setTitle(R.string.choose_bank)
                    .setItems(seq, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                            bankId = bankList.get(i).getId();
                            bankItem.add(bankList.get(i).getAccountName());
                            bankItem.add(bankList.get(i).getAccountNumber());
                            bankItem.add(bankList.get(i).getBranchName());
                            bankItem.add(bankList.get(i).getName());
                            if (totalPrice.contains(","))
                                bankItem.add(totalPrice);
                            else {
                                if (totalPrice.contains("0đ"))
                                    bankItem.add(totalPrice);
                                else
                                    bankItem.add(getString(R.string.full_price_string,
                                            AppUtils.getFullPriceString(Integer.parseInt(totalPrice))));
                            }
                            placeOrder();
                        }
                    }).show();
        }
    }
}
